//登录
var toastTrigger = document.getElementById("liveToastBtn");
var toastLiveExample = document.getElementById("liveToast");
var toast = new bootstrap.Toast(toastLiveExample);
var btn_login = document.querySelector(".btn-login");
var me_uto = document.querySelector(".me-auto");
var toast_body = document.querySelector(".toast-body");
btn_login.addEventListener("click", function () {
  var username = document.getElementById("login-username").value;
  var password = document.getElementById("login-password").value;
  var urlencoded = new URLSearchParams();
  urlencoded.append("username", username);
  urlencoded.append("password", password);

  var requestOptions = {
    method: "POST",
    body: urlencoded,
    redirect: "follow",
  };

  fetch(apirUrl + "/api/login", requestOptions)
    .then((response) => response.json())
    .then((result) => {
      console.log(result);

      //将token保存到本地
      if (result.status === 0) {
        localStorage.setItem("token", result.token);
        if (result.status === 0) {
          var num = 2;

          setInterval(function () {
            me_uto.innerHTML = "登录成功";

            toast_body.innerHTML = "登录成功," + num-- + "秒后进行跳转！";
            toast.show();
            if (num < 0) {
              window.location.href = "./index.html";
            }
          }, 1000);
        }
      }
      if (result.status === 1) {
        if (contains(result.message, "username")) {
          me_uto.innerHTML = "登录失败";
          toast_body.innerHTML =
            "用户名应该为字母数字组合, 且不超过<strong>10</strong>个字符";
          toast.show();
        } else if (contains(result.message, "password")) {
          me_uto.innerHTML = "登录失败";
          toast_body.innerHTML =
            "密码应该为字母数字组合的 <strong>6-12</strong> 位字符";
          toast.show();
        } else if (contains(result.message, "用户名或密码")) {
          me_uto.innerHTML = "登录失败";
          toast_body.innerHTML = result.message;
          toast.show();
        }
      }
    })
    .catch((error) => console.log("error", error));
});
